package jsyf.oa.service.report.reportDayTree;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.system.CheckDao;
import jsyf.oa.dao.system.DepartDao;
import jsyf.oa.dao.system.UserDao;
import jsyf.oa.entity.system.DepartEntity;
import jsyf.oa.facade.report.reportDayTree.ReportDayTreeFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created by jjx on 2018/5/29.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class ReportDayTreeService implements ReportDayTreeFacade {

    @Autowired
    private UserDao userDao;
    @Autowired
    private CheckDao checkDao;
    @Autowired
    private DepartDao departDao;

    class NewJSONObject extends JSONObject {
        @Override
        public boolean equals(Object obj) {
            if (this == obj) return true;//检测this 与 otherObject 是否引用同一个对象
            if (obj == null)//obj 是否为 null(很有必要 )
                return false;
            else if (getClass() != obj.getClass())//比较this 与 obj 是否属于同一个类
                return false;
            String thisId = this.getString("id");
            String objId = ((JSONObject) obj).getString("id");
            if (null != thisId && null != objId) {
                return thisId.equals(objId);
            } else {
                return false;
            }
        }

        @Override
        public int hashCode() {
            String thisName = this.getString("name");
            if (null != thisName) {
                return thisName.hashCode();
            } else {
                return 0;
            }
        }
    }

    @Override
    public List<JSONObject> reportDayTree(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        Set<NewJSONObject> listResult = new HashSet<>();
        List<JSONObject> listCompanies;
        List<JSONObject> listDeparts;
        List<JSONObject> listUsers;
        //第一步 获取所有可以看到的人
        String userIds = checkDao.getChilderByUserId(userId,true);
        //第二步 获取所有可以看到的人的信息
        listUsers = userDao.getViewJSONListByCondition(" AND main=1 AND reportFlag=0 AND jobState !=1 AND id IN(" + userIds + ") " +
                "GROUP BY id ORDER BY companySortNo,departSortNo,roleSortNo,entryDate ", new Object[]{});
        //第三步 获取所有可以看到的人的公司、部门
        listDeparts = userDao.getDepartByUserId(userIds);
        listCompanies = userDao.getCompanyByUserId(userIds);
        List<JSONObject> jsonObjectList = new ArrayList<JSONObject>();
        //添加人员节点
        for (int j = 0; j < listUsers.size(); j++) {
            JSONObject userJSon = new JSONObject();
            JSONObject objUser = listUsers.get(j);
            if ("大区经理".equals(objUser.getString("roleName"))) {
                userJSon.put("name", objUser.getString("name") + "(" + "大区" + ")");
            } else {
                userJSon.put("name", objUser.getString("name"));
            }
            userJSon.put("id", objUser.getString("id"));
            userJSon.put("pId", objUser.getString("departId"));
            userJSon.put("type", "user");
            jsonObjectList.add(userJSon);
        }
        //添加部门节点
        for (int i = 0; i < listDeparts.size(); i++) {
            NewJSONObject newJSONObject = new NewJSONObject();
            JSONObject objDepart = listDeparts.get(i);
            String departId = objDepart.getString("id");
            String parentId = objDepart.getString("parentId");
            String companyId = objDepart.getString("companyId");
            String sortNo = objDepart.getString("sortNo");
            newJSONObject.put("name", objDepart.getString("name"));
            newJSONObject.put("parentId", parentId);
            newJSONObject.put("companyId", companyId);
            if (StringUtils.isEmpty(parentId) || ("0").equals(parentId)) {
                //添加部门的最高节点
                newJSONObject.put("pId", companyId);
                newJSONObject.put("type", "depart");
                newJSONObject.put("dataId", departId);
                newJSONObject.put("id", departId);
                newJSONObject.put("isParent", true);
                newJSONObject.put("sortNo", sortNo);
                listResult.add(newJSONObject);
            } else {
                //递归获取最上层部门
                getPranentId(listResult, newJSONObject);
                //添加部门的一般节点
                newJSONObject.put("pId", parentId);
                newJSONObject.put("type", "depart");
                newJSONObject.put("dataId", departId);
                newJSONObject.put("id", departId);
                newJSONObject.put("isParent", true);
                newJSONObject.put("sortNo", sortNo);
                listResult.add(newJSONObject);
            }
        }
        //根节点root
        JSONObject objRoot = new JSONObject();
        objRoot.put("id", "0");
        objRoot.put("name", "组织机构");
        objRoot.put("type", "root");
        objRoot.put("open", true);
        objRoot.put("isParent", true);
        jsonObjectList.add(objRoot);
        if (null != listResult || listResult.size() > 0) {
            for (JSONObject jsonObject : listResult) {
                jsonObjectList.add(jsonObject);
            }
        }
        //部门排序
        Comparator<JSONObject> comparator = new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject jsonObject1, JSONObject jsonObject2) {
                if (null == jsonObject1 || null == jsonObject2) {
                    return -2;
                }
                //根据部门的sortNo排序
                if (jsonObject1.getString("type").equals("depart") || jsonObject2.getString("type").equals("depart")) {
                    if (jsonObject1.getString("type").equals("depart") && jsonObject2.getString("type").equals("depart")) {
                        return Integer.parseInt(jsonObject1.getString("sortNo")) - Integer.parseInt(jsonObject2.getString("sortNo"));
                    } else {
                        return 100;
                    }
                } else {
                    return -2;
                }
            }
        };
        Collections.sort(jsonObjectList, comparator);
        //添加公司节点
        for (int i = 0; i < listCompanies.size(); i++) {
            JSONObject objCompany = listCompanies.get(i);//id,name,sortNo,
            String parentId = objCompany.getString("parentId");
            if ("0".equals(listCompanies.get(0).getString("parentId"))) {
                if (StringUtils.isEmpty(parentId) || ("0").equals(parentId)) {
                    objCompany.put("pId", "0");
                    objCompany.put("open", true);
                } else {
                    objCompany.put("pId", parentId);
                    objCompany.put("open", false);
                }
            } else {
                objCompany.put("pId", "0");
                objCompany.put("open", true);
            }
            objCompany.put("type", "company");
            objCompany.put("isParent", true);
            jsonObjectList.add(objCompany);
        }
        return jsonObjectList;
    }

    //递归获取最上层部门
    private void getPranentId(Set<NewJSONObject> listResult, JSONObject newJSONObject) {
        String parentId = newJSONObject.getString("parentId");
        NewJSONObject parentDepart = new NewJSONObject();
        //获取上级部门信息
        DepartEntity departEntity = (DepartEntity) departDao.getIBaseEntityById(parentId);
        String newParentId = departEntity.getParentId();
        if (StringUtils.isEmpty(newParentId) || ("0").equals(newParentId)) {
            //添加传来部门的高节点部门
            parentDepart.put("name", departEntity.getName());
            parentDepart.put("parentId", departEntity.getParentId());
            parentDepart.put("companyId", departEntity.getCompanyId());
            parentDepart.put("pId", departEntity.getCompanyId());
            parentDepart.put("type", "depart");
            parentDepart.put("dataId", departEntity.getId());
            parentDepart.put("id", departEntity.getId());
            parentDepart.put("isParent", true);
            parentDepart.put("sortNo", departEntity.getSortNo());
            listResult.add(parentDepart);
        } else {
            parentDepart.put("name", departEntity.getName());
            parentDepart.put("parentId", departEntity.getParentId());
            parentDepart.put("companyId", departEntity.getCompanyId());
            parentDepart.put("pId", departEntity.getParentId());
            parentDepart.put("type", "depart");
            parentDepart.put("dataId", departEntity.getId());
            parentDepart.put("id", departEntity.getId());
            parentDepart.put("isParent", true);
            parentDepart.put("sortNo", departEntity.getSortNo());
            parentDepart.put("parentId", departEntity.getParentId());
            listResult.add(parentDepart);
            getPranentId(listResult, parentDepart);
        }
    }

}
